//
//  SAReturnGoodsListDetailVC.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/7/20.
//

#import "SAReturnGoodsListDetailVC.h"
#import "SAReturnGoodsListDetailCell.h"
#import "SASaleDocumentsHeaderView.h"
#import "SASalesInvoiceDetailAPI.h"
#import "SASalesInvoiceDetailModel.h"

@interface SAReturnGoodsListDetailVC ()<UITableViewDelegate, UITableViewDataSource, HTTPAPIDelegate>

@property (nonatomic, strong) NSString *saleOrderId;
@property (nonatomic, strong) NSString *saleOrderNo;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *checkBtn;

@property (nonatomic, strong) UILabel *vipLab;
@property (nonatomic, strong) UILabel *dateLab;

@property (nonatomic, strong) SASalesInvoiceDetailAPI *salesInvoiceDetailAPI;
@property (nonatomic, strong) SASalesInvoiceDetailModel *salesInvoiceDetailModel;

@end

@implementation SAReturnGoodsListDetailVC

-(instancetype)initWithSaleOrderId:(NSString *)saleOrderId AndSaleOrderNo:(NSString *)saleOrderNo{
    if (self = [super init]) {
        self.saleOrderId = saleOrderId;
        self.saleOrderNo = saleOrderNo;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    if (self.salesInvoiceDetailAPI == api) {
        self.salesInvoiceDetailModel = [SASalesInvoiceDetailModel mj_objectWithKeyValues:data[@"data"]];
        if (self.salesInvoiceDetailModel.memberName.length == 0) {
            self.salesInvoiceDetailModel.memberName = @"散客";
        }
        if (self.salesInvoiceDetailModel.mobile.length > 0) {
            self.vipLab.text = [NSString stringWithFormat:@"%@(%@)",self.salesInvoiceDetailModel.memberName,self.salesInvoiceDetailModel.mobile];
        }else {
            self.vipLab.text = self.salesInvoiceDetailModel.memberName;
        }
        self.dateLab.text = self.salesInvoiceDetailModel.createTime;
        [self.tableView reloadData];
        BOOL allReturn = NO;
        for (SAProductListModel *list in self.salesInvoiceDetailModel.productList) {
            BOOL isReturn = NO;
            for (SASaleSkuListModel *model in list.skuList) {
                model.stock = @"0";
                model.productName = list.productName;
                model.productId = list.productId;
                model.img = list.img;
                NSInteger returnCount = [model.count integerValue] - [model.returnCount integerValue];
                if (returnCount > 0) {
                    isReturn = YES;
                    allReturn = YES;
                    model.isReturn = YES;
                }else {
                    model.isReturn = NO;
                }
            }
            list.isReturn = isReturn;
        }
        self.checkBtn.hidden = !allReturn;
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
  
}

#pragma mark - UITableView Delegate & DataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.salesInvoiceDetailModel.productList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.salesInvoiceDetailModel.productList[section].skuList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SAReturnGoodsListDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SAReturnGoodsListDetailCell" forIndexPath:indexPath];
    SASaleSkuListModel *model = self.salesInvoiceDetailModel.productList[indexPath.section].skuList[indexPath.row];
    cell.model = model;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kScaleNum(40);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    SASaleDocumentsHeaderView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"SASaleDocumentsHeaderView"];
    SAProductListModel *model = self.salesInvoiceDetailModel.productList[section];
    header.returnModel = model;
    return header;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kScaleNum(40);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return kScaleNum(0.5);
}

#pragma mark - event
-(void)clickedCheckBtn {
    
    BOOL allReturn = YES;
    double returnTotal = 0.f;
    NSMutableArray *marr = [NSMutableArray array];
    for (SAProductListModel *list in self.salesInvoiceDetailModel.productList) {
        for (SASaleSkuListModel *model in list.skuList) {
            returnTotal += [model.returnCount integerValue] * [model.skuActualPrice doubleValue]/100;
            NSInteger stock = [model.stock integerValue];
            if (stock > 0) {
                [marr addObject:model];
            }
            NSInteger returnCount = [model.count integerValue] - [model.returnCount integerValue];
            if (returnCount -  stock> 0) {
                allReturn = NO;
            }
        }
    }
    self.salesInvoiceDetailModel.isAllReturn = allReturn;
    self.salesInvoiceDetailModel.returnTotal = returnTotal;
    
    if (marr.count == 0) {
        [Prompt popPromptViewWithMsg:@"请选择需退货的商品" duration:2];
    }else {
        
        !self.selectBlock ?: self.selectBlock(marr, self.salesInvoiceDetailModel);
    }
}

#pragma mark - initUI
-(void)initUI {
    [self setNavigationItemBackBBIAndTitle:self.saleOrderNo];
    [self setBgImage:nil];
    
    UIButton *checkBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    checkBtn.frame = CGRectMake(0, 0, kScaleNum(60), kScaleNum(44));
    [checkBtn setImage:[UIImage imageNamed:@"return_check"] forState:UIControlStateNormal];
    [checkBtn addTarget:self action:@selector(clickedCheckBtn) forControlEvents:UIControlEventTouchUpInside];
    [self addRightViews:@[checkBtn]];
    self.checkBtn = checkBtn;
    
    NSArray *arr = @[@"  会员", @"  日期"];
    NSArray *iconArr = @[@"Sale_vip", @"Sale_clock"];
    
    for (int i = 0; i < arr.count; i++) {
        UIButton *titleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        titleBtn.frame = CGRectMake(kScaleNum(20), kScaleNum(StatusHeight + 45 * i), kScaleNum(80), kScaleNum(45));
        [titleBtn setTitle:arr[i] forState:UIControlStateNormal];
        [titleBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
        titleBtn.titleLabel.font = kFont(15);
        [titleBtn setImage:[UIImage imageNamed:iconArr[i]] forState:UIControlStateNormal];
        titleBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [self.view addSubview:titleBtn];
        
        UILabel *contentLab = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWidth - kScaleNum(220), kScaleNum(StatusHeight + 45 * i), kScaleNum(200), kScaleNum(45))];
        contentLab.font = kFont(15);
        contentLab.textAlignment = NSTextAlignmentRight;
        contentLab.textColor = kLightgGrayColor;
        [self.view addSubview:contentLab];
        
        if (i == 0) {
            self.vipLab = contentLab;
        }else if (i == 1) {
            self.dateLab = contentLab;
        }
        
        if (i == 0) {
            UIView *line = [[UIView alloc] initWithFrame:CGRectMake(kScaleNum(20), kScaleNum(StatusHeight + 45 * i + 44.5), kScreenWidth - kScaleNum(40), kScaleNum(0.5))];
            line.backgroundColor = kBgColor;
            [self.view addSubview:line];
        }
    }
    
    UIView *grayView = [[UIView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight + 45 * 2), kScreenWidth, kScaleNum(30))];
    grayView.backgroundColor = kColor(228, 231, 243, 1);
    [self.view addSubview:grayView];
    NSArray *arr2 = @[@"商品", @"可退数量", @"单价", @"实付", @"退货"];
    for (int i = 0; i < arr2.count; i++) {
        UILabel *titleLab = [[UILabel alloc] init];
        titleLab.text = arr2[i];
        titleLab.font = kFont(14);
        titleLab.textColor = kLightgGrayColor;
        [grayView addSubview:titleLab];
        titleLab.textAlignment = NSTextAlignmentCenter;
        if (i == 0) {
            titleLab.frame = CGRectMake(kScaleNum(20), 0, kScaleNum(75), kScaleNum(30));
            titleLab.textAlignment = NSTextAlignmentLeft;
        }else if (i == 1) {
            titleLab.frame = CGRectMake(kScaleNum(100), 0, kScaleNum(60), kScaleNum(30));
        }else if (i == 2) {
            titleLab.frame = CGRectMake(kScaleNum(160), 0, kScaleNum(55), kScaleNum(30));
        }else if (i == 3) {
            titleLab.frame = CGRectMake(kScaleNum(215), 0, kScaleNum(55), kScaleNum(30));
        }else if (i == 4) {
            titleLab.frame = CGRectMake(kScaleNum(270), 0, kScaleNum(105), kScaleNum(30));
        }
    }
    
    [self.view addSubview:self.tableView];
    
    self.salesInvoiceDetailAPI.salesOrderId = self.saleOrderId;
    [self.salesInvoiceDetailAPI sendRequestToServerWithActivityViewAndMask:GET];
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight + 120), kScreenWidth, kScreenHeight - kScaleNum(StatusHeight + 120)) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = kBgColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        [_tableView registerClass:[SASaleDocumentsHeaderView class] forHeaderFooterViewReuseIdentifier:@"SASaleDocumentsHeaderView"];
        [_tableView registerClass:[SAReturnGoodsListDetailCell class] forCellReuseIdentifier:@"SAReturnGoodsListDetailCell"];
    }
    return _tableView;
}

-(SASalesInvoiceDetailAPI *)salesInvoiceDetailAPI {
    if (!_salesInvoiceDetailAPI) {
        _salesInvoiceDetailAPI = [SASalesInvoiceDetailAPI apiWithDelegate:self];
    }
    return _salesInvoiceDetailAPI;
}

@end
